package com.homegoods.login.presenter;

import android.content.Context;
import android.databinding.ObservableField;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.homegoods.aroutercomment.ARouterPath;
import com.homegoods.login.ApiUtil;
import com.homegoods.login.KGetVerHelper;
import com.homegoods.login.R;
import com.homegoods.login.evnet.LoginSucEvent;
import com.homegoods.login.model.AuthCodeLoginParams;
import com.homegoods.login.model.UserModel;
import com.homegoods.login.model.UserParams;
import com.homegoods.login.model.UserProxy;
import com.homegoods.login.view.LoginSmsView;
import com.homegoods.resource.HomeGoodsApp;
import com.kedll.library.KBaseApplication;
import com.kedll.library.mvp.BasePresenter;
import com.kedll.library.util.RxBus;
import com.kedll.library.util.SharePreUtils;
import com.kedll.library.util.StringUtil;
import com.kedll.library.util.SystemUtils;
import com.kedll.library.util.ToastUtil;
import com.network.utils.NetworkUtils;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.functions.Consumer;

/**
 * 验证码登录Presenter
 *
 * @author QiQi
 * @date 2017/4/29
 */

public class LoginSmsPresenter extends BasePresenter<LoginSmsView> {
    private static final String TAG = "LoginSmsPresenterTag";
    /**
     * 手机号
     */
    public final ObservableField<String> strPhoneNumber = new ObservableField<>();
    /**
     * 验证码
     *
     */
    public final ObservableField<String> strVer = new ObservableField<>();
    private KGetVerHelper kGetVerHelper;
    private String smsId;


    public LoginSmsPresenter(KGetVerHelper kGetVerHelper, LoginSmsView view) {
        super(view);
        this.kGetVerHelper = kGetVerHelper;
    }


    /**
     * 跳转到账号密码登录
     *
     * @param view
     */
    public void toRegisterClicked(View view) {
        mView.showLoginView();
    }

    /**
     * 获取验证码
     *
     * @param view
     */
    public void onGetVerClickListener(View view) {
        if (checkGetVerCodeData()) {
            getVerCode();
        }
    }

    /**
     * 检查获取验证码是数据的合法性
     *
     * @return
     */
    private boolean checkGetVerCodeData() {
        String phone = strPhoneNumber.get();
        if (!StringUtil.isPhoneNum(phone)) {
            ToastUtil.showToast(R.string.string_hint_phone);
            return false;
        }
        return true;
    }

    /**
     * 获取短信验证码
     */
    private void getVerCode() {
        ApiUtil.getVerCodeToLogin(strPhoneNumber.get(), jsonElement -> {
            Log.d(TAG, "accept: jsonElement == " + jsonElement);
            kGetVerHelper.sendSuc();
            ToastUtil.showToast(jsonElement);
        }, throwable -> Log.d(TAG, "getVerCode: throwable == " + throwable.toString()));
    }

    /**
     * 登录
     *
     * @param view
     */
    public void loginClicked(View view) {
        if (checkLoginData(view)) {
            login(view);
        }
    }


    /**
     * 检查登录所需数据的合法性
     *
     * @return
     */
    private boolean checkLoginData(View view) {
        String phone = strPhoneNumber.get();
        String pwd = strVer.get();
        //手机号不能为空
        if (StringUtil.isEmpty(phone)) {
            ToastUtil.showSnackbar(view, R.string.string_hint_phone);
            return false;
        }

        if (!StringUtil.checkPassword(pwd)) {
            ToastUtil.showSnackbar(view, "验证码不能为空");
            return false;
        }

        return true;
    }

    /**
     * 验证码登录
     *
     * @param view
     */
    protected void login(final View view) {
        mView.hideKeyBoard();
        mView.showLoad(view.getContext().getString(R.string.login_posting));
        AuthCodeLoginParams params = new AuthCodeLoginParams();
        params.setTelephone(strPhoneNumber.get());
        params.setAuthCode(strVer.get());
        Log.d(TAG, "login: params == " + JSON.toJSONString(params));
        //                LoginSmsPresenter.this.pushDevice(userBean);
        ApiUtil.userPhoneLogin(/*strPhoneNumber.get(),strVer.get()*/params, new Consumer<UserModel>() {
            @Override
            public void accept(UserModel userBean) throws Exception {
                userBean.setMPhone(strPhoneNumber.get());
                LoginSmsPresenter.this.loginOrRegisterSuc(userBean);
            }
        }, throwable -> {
            mView.hideLoad();
            ToastUtil.showSnackbar(view, "登录失败");
        });
    }

    public void qqLogin(String accessToken) {
        ApiUtil.qqLogin(accessToken, e -> {
            tokenGetUserInfo(e.getToken(), e.getSid());
        }, throwable -> {
            mView.hideLoad();
        });
    }

    /**
     * 获取用户信息
     *
     * @param token
     * @param sid
     */
    private void tokenGetUserInfo(String token, String sid) {
        ApiUtil.tokenGetUserInfo(token, sid, userModel -> {
            pushDevice(userModel);
        }, throwable -> {
        });
    }

    /**
     * 用户协议
     *
     * @param view
     */
    public void userAgreement(View view) {
        ARouter.getInstance()
                .build(ARouterPath.PATH_USER_AGREEMENT)
                .navigation();
    }

    /**
     * 上传设备信息
     *
     * @param userBean
     */
    private void pushDevice(final UserModel userBean) {
        Map<String, Object> map = new HashMap<>();
        map.put("dtype", "Android");
        map.put("dwsinf", SystemUtils.getManufacture());
        map.put("otype", SystemUtils.getOSVersion());
        map.put("dtoken", SystemUtils.getDeviceModel());
        map.put("appname", "安卓端" + SystemUtils.getMyVersionCode());
        map.put("marker", "");
        //首次登录成功后上传设备信息
        ApiUtil.postDeviceInfo(userBean.getToken(), map, s -> { //modify shibo.zheng
            loginOrRegisterSuc(userBean);
        }, throwable -> {
        });
    }

    /**
     * 登录或注册成功
     */
    private void loginOrRegisterSuc(final UserModel userBean) {
        mView.hideLoad();
        //保存用户数据
        UserProxy.getInstance().saveClientUser(userBean);
//        PrintControllerUtil.setPushMsgConfig(MyApplication.getInstance(), UserProxy.getInstance().getUserID());
        SharePreUtils.addUser(KBaseApplication.getInstance(), userBean.getMPhone());
        Log.d(TAG, "loginOrRegisterSuc: userBean.getToken == " + userBean.getToken());
        UserProxy.getInstance().saveClientUser(userBean);
        HomeGoodsApp.setToken(userBean.getToken()); //modify shibo.zheng
        NetworkUtils.saveToken(userBean.getToken());    //临时方案：存储token到network中，在httpManager中取
        RxBus.getDefault().post(new LoginSucEvent());
    }

    /**
     * 收不到验证码
     *
     * @param view
     */
    public void resetPwd(View view) {
        mView.haveNoVercorde();
    }


    /**
     * 获取登录过的账号
     *
     * @param context
     */
    public void initAutoComplete(Context context) {
        JSONArray array = SharePreUtils.getUsers(context);
        int size = array.size();
        size = size > 5 ? 5 : size;
        if (size > 0) {
            String[] users = new String[size];
            for (int i = 0; i < size; i++) {
                users[i] = array.get(i).toString();
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<>(context, R.layout.spinner_item, users);
            mView.setAutoTextViewAdapter(adapter);
        }
    }
}
